var express = require('express');
var router = express.Router();

//引入模型
const commodityModel = require("../models/commodity");
//请求商品列表
router.post('/goodslist', function (req, res, next) {
  //get req.query
  //post req.body
  let page = req.body.page || 1;
  let count = req.body.count || 6;
  commodityModel.find({}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc,
    })
  }).skip((page - 1) * count).limit(count);
});
//搜索商品
router.get('/search', function (req, res, next) {
  //get req.query
  //post req.body
  commodityModel.find({}, (err, doc) => {
    if (err) throw err;
    // 存放筛选出的商品
    let resarr = [];
    doc.forEach(val => {
      //字面量创建正则
      var reg = new RegExp(req.query.cname, 'g');
      if (reg.test(val.productName + val.title)) {
        resarr.push(val);
      }
    })
    if (resarr.length === 0) {
      res.json({
        status: 6,
        msg: '未找到商品',
      })
    } else {
      res.json({
        status: 0,
        result: resarr,
      })
    }
  });
});
//获取商品详情
router.get('/detail', function (req, res, next) {
  //get req.query
  //post req.body
  console.log(req.query.pid);
  commodityModel.find({productId:req.query.pid}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc,
    })
  });
});


module.exports = router;
